package com.sqlcheck.controller;

import com.sqlcheck.common.response.ApiResponse;
import com.sqlcheck.dto.response.DashboardStatisticsVO;
import com.sqlcheck.service.DashboardService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@RestController
@RequestMapping("/dashboard")
@RequiredArgsConstructor
public class DashboardController {

    private final DashboardService dashboardService;

    /**
     * 获取仪表盘统计信息
     */
    @GetMapping("/statistics")
    public ApiResponse<DashboardStatisticsVO> getStatistics(@RequestParam(required = false) Long userId) {
        try {
            // 如果没有传递userId，尝试从上下文获取当前用户ID
            if (userId == null) {
                userId = getCurrentUserId(); // 从安全上下文获取
                log.debug("从上下文获取到用户ID: {}", userId);
            }
            
            DashboardStatisticsVO statistics = dashboardService.getDashboardStatistics(userId);
            return ApiResponse.success(statistics);
        } catch (Exception e) {
            log.error("获取仪表盘统计信息失败", e);
            return ApiResponse.error("获取仪表盘统计信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取当前用户ID（从认证上下文）
     */
    private Long getCurrentUserId() {
        try {
            // 从请求上下文获取用户ID（由AuthInterceptor注入）
            ServletRequestAttributes servletRequestAttributes = 
                (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            jakarta.servlet.http.HttpServletRequest request = servletRequestAttributes.getRequest();
            Object userId = request.getAttribute("X-User-ID");
            if (userId instanceof Long) {
                return (Long) userId;
            }
        } catch (Exception e) {
            log.warn("无法从请求上下文获取用户ID", e);
        }
        
        // 如果无法获取到用户ID，返回null让前端明确传递
        log.warn("无法获取当前用户ID，请确保前端传递userId参数或正确设置认证信息");
        return null;
    }

    /**
     * 获取任务统计信息
     */
    @GetMapping("/task-statistics")
    public ApiResponse<DashboardStatisticsVO.TaskStatistics> getTaskStatistics(
            @RequestParam(required = false) Long userId) {
        try {
            // 如果没有传递userId，尝试从上下文获取当前用户ID
            if (userId == null) {
                userId = getCurrentUserId();
                log.debug("从上下文获取到用户ID: {}", userId);
            }
            
            DashboardStatisticsVO.TaskStatistics taskStats = dashboardService.getTaskStatistics(userId);
            return ApiResponse.success(taskStats);
        } catch (Exception e) {
            log.error("获取任务统计信息失败", e);
            return ApiResponse.error("获取任务统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取SQL语句统计信息
     */
    @GetMapping("/sql-statistics")
    public ApiResponse<DashboardStatisticsVO.SqlStatementStatistics> getSqlStatistics(
            @RequestParam(required = false) Long userId) {
        try {
            // 如果没有传递userId，尝试从上下文获取当前用户ID
            if (userId == null) {
                userId = getCurrentUserId();
                log.debug("从上下文获取到用户ID: {}", userId);
            }
            
            DashboardStatisticsVO.SqlStatementStatistics sqlStats = dashboardService.getSqlStatementStatistics(userId);
            return ApiResponse.success(sqlStats);
        } catch (Exception e) {
            log.error("获取SQL统计信息失败", e);
            return ApiResponse.error("获取SQL统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取最近任务列表
     */
    @GetMapping("/recent-tasks")
    public ApiResponse<java.util.List<DashboardStatisticsVO.RecentTaskVO>> getRecentTasks(
            @RequestParam(defaultValue = "5") Integer limit,
            @RequestParam(required = false) Long userId) {
        try {
            // 如果没有传递userId，尝试从上下文获取当前用户ID
            if (userId == null) {
                userId = getCurrentUserId();
                log.debug("从上下文获取到用户ID: {}", userId);
            }
            
            java.util.List<DashboardStatisticsVO.RecentTaskVO> recentTasks = dashboardService.getRecentTasks(limit,
                    userId);
            return ApiResponse.success(recentTasks);
        } catch (Exception e) {
            log.error("获取最近任务列表失败", e);
            return ApiResponse.error("获取最近任务列表失败: " + e.getMessage());
        }
    }
}